package com.melon.web;

import com.melon.config.AppConfig;
import com.melon.domain.GeneralObjectResp;
import com.melon.entity.admin.User;
import com.melon.service.RedisService;
import com.melon.service.UserService;
import com.melon.utils.EncryptUtil;
import com.melon.utils.GSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by zhiqi.shao on 2017/3/14.
 */
@Slf4j
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AppConfig appConfig;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String loginIndex(){
        return "user/login";
    }


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object login(User user){
        String msg=null;
        //得到Subject及创建用户名/密码身份验证Token（即用户身份/凭证）
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
            if (!subject.isAuthenticated()) {
                return "user/login";
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败";
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
        }
        if(!StringUtils.isEmpty(msg)){
            return GeneralObjectResp.failure(msg);
        }
        return GeneralObjectResp.success(null);
    }




    @RequestMapping("/registIndex")
    public String registIndex(){
        return "user/register";
    }


    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    @ResponseBody
    public Object regist(User user){
        log.info("请求报文: {}", GSON.toJson(user));
        user.setPassword(EncryptUtil.md5(user.getPassword(),appConfig.getSalt()));
        User u=userService.save(user);
        if(u!=null){
            return GeneralObjectResp.success(null);
        }
        return GeneralObjectResp.failure("保存失败");
    }


    @RequestMapping("/adminIndex")
    @RequiresPermissions("角色管理")
    public String adminIndex(){
        return "user/adminIndex";
    }

    @RequestMapping("/adminOut")
    public String adminLoginout(){
        return "user/login";
    }

    @RequestMapping("/test")
    public String test(){
        return "user/test";
    }
}
